

var myWebrtc = {
    iceServer: {
        "iceServers": [{
            "urls": "stun:stun.stunprotocol.org"
        }]
    },
    pc: new RTCPeerConnection(this.iceServer),
    remoteName: '',
    dataChannal: undefined,

    video1: document.getElementById('video1'),
    video2: document.getElementById('video2'),
    // 初始化RTCPeerConnection对象，增加回调事件
    initWebrtc() {
        this.pc.onicecandidate = (event) => {
            if (event.candidate) {
                console.log('has candidate')
                ws.emit('candidate', {
                    name: ws.id,
                    target: this.remoteName,
                    type: "candidate",
                    candidate: event.candidate
                })
                // Send the candidate to the remote peer
            } else {
                // All ICE candidates have been sent
                console.log(`hasn't candidate`)
            }
        };
        // 处理流
        if (this.pc.addTrack !== undefined) {
            this.pc.ontrack = ev => {
                console.log('ontrack')

                var video2 = document.getElementById('video2');
                if (ev.streams && ev.streams[0]) {
                    video2.srcObject = ev.streams[0];
                } else {
                    var inboundStream;
                    if (!inboundStream) {
                        inboundStream = new MediaStream();
                        video2.srcObject = inboundStream;
                    }
                    inboundStream.addTrack(ev.track);
                }
            }
        } else {
            this.pc.onaddstream = ev => {
                console.log('onaddstream')
                doAddStream(ev.stream);
            }
        }
        // 文字数据通道
        this.pc.ondatachannel = (ev) => {
            console.log('Data channel is created!');
            this.dataChannal = ev.channel;
            this.setDataChannel();
        };
        this.startVideo();
    },

    startVideo() {
        navigator.mediaDevices.getUserMedia({
            audio: true,
            video: {
                width: this.video1.width || 400,
                height: this.video1.height || 300,
                // frameRate: {
                //     ideal: 10,
                //     max: 15
                // },
                // facingMode: { exact: "environment" } // 强制使用后置摄像头
                facingMode: "user", // 前置摄像头
            }
        })
            .then((stream) => {
                for (const track of stream.getTracks()) {
                    this.pc.addTrack(track, stream);
                }
                console.info('then video begin');
                if (this.video1 == null) {
                    console.log('not found vodeo element')
                } else {
                    // Older browsers may not have srcObject
                    if ("srcObject" in this.video1) {
                        this.video1.srcObject = stream;
                        console.log('stream');
                        window.stream = stream;
                    } else {
                        // Avoid using this in new browsers, as it is going away.
                        this.video1.src = (window.URL || window.webkitURL).createObjectURL(stream);
                    }
                    console.info('then video success');
                }
            })
            .catch((err) => {
                console.error('catch error;');
                console.error(err.name + ": " + err.message);
            });
    },


    // offer 创建offer同时设置本地sdp
    createOffer() {
        this.pc.createOffer({ iceRestart: true }).then((offer) => {
            this.pc.setLocalDescription(offer);
            console.log('%c 【create offer】success', 'color:green;');
        }).catch(err => {
            console.log('%c 【create offer】error', 'color:red;');
            console.log(err);
        })
    },
    // 开始建立连接，传递本地sdp
    establish(toid) {
        this.remoteName = toid;
        ws.emit('establishConnect', {
            name: ws.id,
            target: toid,
            type: "video-offer",
            sdp: this.pc.localDescription
        });
    },
    // offer 设置远程sdp
    setRemoteSDP(data) {
        this.pc.setRemoteDescription(data.sdp).then(() => {
            console.log('%c 【offer set remote sdp】success', 'color:green;');
        }).catch(err => {
            console.log('%c 【offer set remote sdp】 error', 'color:red;');
            console.log(err);
        })
    },
    // answer 设置远程sdp，并创建answer同时设置本地sdp，然后传递本地sdp
    createAnswer(data) {
        this.pc.setRemoteDescription(new RTCSessionDescription(data.sdp)).then(() => {
            console.log('%c 【answer set remote sdp】success', 'color:green;');
            return this.pc.createAnswer({ iceRestart: true }).then((answer) => {
                console.log('%c 【create answer】 success', 'color:green;');
                return this.pc.setLocalDescription(answer);
            })
        }).then(() => {
            this.remoteName = data.name;
            ws.emit('establishConnect', {
                name: ws.id,
                target: data.name,
                type: "video-answer",
                sdp: this.pc.localDescription
            });
        }).catch(err => {
            console.log('%c 【answer set remote sdp】 and 【create answer】 error', 'color:red;');
            console.log(err);
        })
    },
    // 通过远端发过来的ICE候选地址，添加一个的ICE代理
    addCandidate(data) {
        this.pc.addIceCandidate(new RTCIceCandidate(data.candidate)).then(() => {
            console.log('%c 【add candidate】 success', 'color:green;');
        }).catch(err => {
            console.log('%c 【add candidate】error', 'color:red;');
            console.log(err);
        })
    },
    // 创建channel
    createChannel() {
        this.dataChannal = this.pc.createDataChannel(ws.id);
        this.setDataChannel();
    },
    setDataChannel() {
        this.dataChannal.onopen = () => {
            this.dataChannal.send("Hello World!");
        };

        this.dataChannal.onmessage = (event) => {
            document.getElementById('text1').value += event.data + '\n';
        };

        this.dataChannal.onclose = () => {
            console.log("The Data Channel is Closed");
        };
        this.dataChannal.onerror = (error) => {
            console.log("Data Channel Error:", error);
        };
    }
}

myWebrtc.initWebrtc();

